﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Thaire.Investment.Common;
//using ThaireInvestmentWeb.BusinessDelegate;
using ThaireInvestmentWeb.Models;
using ThaireInvestmentWeb.Util;
using ThaireInvestmentWeb.WcfSerivce;

namespace ThaireInvestmentWeb.Controllers
{
    public class InstructionController : Controller
    {
        // GET: /Instruction/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult ManageInstruction(int? page)
        {
            ManageInstructionModel model = new ManageInstructionModel();
           
            try
            {
                if (page.GetValueOrDefault() == 0)
                {

                    ManageInstructionScreenData screenData = ServiceFactory.GetService().GetManageInstructionScreenData();
                    model = ManageInstructionModel.Build(screenData);
                }
                else //มาจาก page grid click
                {
                    model = (ManageInstructionModel)TempData["ManageInstructionModel"];
                }
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["ManageInstructionModel"] = model; 
            return View(model);
        }
        [HttpPost]
        public ActionResult ManageInstruction(ManageInstructionModel model)
        {
            ManageInstructionModel oldModel = (ManageInstructionModel)TempData["ManageInstructionModel"];
            try
            {
                if (!String.IsNullOrEmpty(model.BtnSearch))
                {
                  //  oldModel.ManageInstructionDTOList = new List<ManageInstructionDTO>();
                    List<ManageInstructionDTO> searchData = Search(model);
                    oldModel.ManageInstructionDTOList = searchData;
                    if (searchData.Count==0)
                      ViewBagUtil.SetInfo(ViewBag,"ไม่พบข้อมูล", null);
                }

            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["ManageInstructionModel"] = oldModel;
            return View(oldModel);
        }
        private List<ManageInstructionDTO> Search(ManageInstructionModel model)
        {

            return  new List<ManageInstructionDTO>(ServiceFactory.GetService().SearchInstructionDTO(model.ToSearchInstructionFilter()));
                
            
        }
                            
        public ActionResult EditInstruction(int headerID)
        {
            InstructionFormModel model = new InstructionFormModel();
            try
            {
                InstructionFormScreenData scrData = ServiceFactory.GetService().GetInstructionFormScreenData(headerID);
              model.SetData(scrData);
             
              model.Updatemode = true;
            }
            catch(Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["InstructionFormModel"] = model;
           // return RedirectToAction("InstructionForm", model);
           return View("InstructionForm",model);
        }
        public ActionResult InstructionForm(int? page)
        {
            InstructionFormModel model = new InstructionFormModel();
            try
            {
                if (page.HasValue)
                {
                    model = (InstructionFormModel)TempData["InstructionFormModel"];
                }
                else
                {
                    InstructionFormScreenData screenData = ServiceFactory.GetService().GetInstructionFormScreenData(0);
                    model.SetData(screenData);
                }
                TempData["InstructionFormModel"] = model; 
            }
            catch (Exception ex)
            {
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View(model);
        
        }


        public ActionResult GetAssetClass(int instrumentID)
        {
            InstructionFormModel oldModel = (InstructionFormModel)TempData["InstructionFormModel"];
            TempData["InstructionFormModel"] = oldModel;
            oldModel.FinancialInstrumentAssetClassList = new BindingList<SelectListItem>();
            oldModel.FinancialInstrumentAssetClassList.Insert(0, WebUtil.SelectListSelectDefault());
            var data = oldModel.InstructionFormScreenDataCache.AssetClassList.Where(x => x.FinancialInstrumentsReferenceCodeID == instrumentID).ToList();
            foreach (var item in data)
            {
                oldModel.FinancialInstrumentAssetClassList.Add(new SelectListItem() { Text = item.AssetClassEN, Value = item.AssetClassID.ToString() });

            }


            return Json(data);

            //   return View(oldModel);
        }

        [HttpPost]
        public ActionResult InstructionForm(InstructionFormModel model)
        {
           
            InstructionFormModel oldModel = (InstructionFormModel)TempData["InstructionFormModel"];
            oldModel.TradeDate = model.TradeDate;
            oldModel.SettlementDate = model.SettlementDate;
            try
            {
                if (!String.IsNullOrEmpty(model.BtnGetSelection))
                {
                    ReferenceCode financialInstrument = oldModel.InstructionFormScreenDataCache.FinancialInstrumentList.Where(x => x.ID == DataConverter.ConvertStringToIntNull(model.FinancialInstrument).GetValueOrDefault()).SingleOrDefault();

                    if (financialInstrument == null)
                        throw new Exception("ไม่พบ RefCode");

                    oldModel.InstrumentType = CommonUtil.GetInstrumentType(financialInstrument.Key);

                    if (oldModel.InstrumentType == InstrumentType.FixedIncome )//fixIncome
                    {
                        oldModel.TransactionDataGridAdapterList = GetSelectionFixIncome(model);
                    }
                    else if (oldModel.InstrumentType == InstrumentType.UnitTrust)//unit Trust
                    {
                        oldModel.TransactionDataGridAdapterList = GetSelectionUnitTrust(model);
                    }
                    else if (oldModel.InstrumentType == InstrumentType.Equity)//
                    {
                        oldModel.TransactionDataGridAdapterList = GetSelectionEquity(model);
                    }
                    else if (oldModel.InstrumentType == InstrumentType.DepositAtFinancial)//
                    {
                        oldModel.TransactionDataGridAdapterList = GetSelectionDepositAtFinancial(model);
                    }
                    //   financialInstrument.Where
                   
                    if (oldModel.TransactionDataGridAdapterList.Count == 0)
                        ViewBagUtil.SetInfo(ViewBag, "ไม่พบข้อมูล", null);
                }
                else if (!String.IsNullOrEmpty(model.BtnAdd))
                {
                    AddInstruction(model, oldModel);
                    //ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", null);
                }
                else if (!String.IsNullOrEmpty(model.DeleteInstructionKey))
                {
                    DelInstruction(model.DeleteInstructionKey, oldModel);
                    ModelState["DeleteInstructionKey"].Value = null;//clear stage
                    ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", null);

                }
                else if (!String.IsNullOrEmpty(model.BtnSave))
                {

                    oldModel.SetData(UpdateOrInsert(model, oldModel));
                    oldModel.Updatemode = true;
                    ModelState.Clear();
                    ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", null);
                }
                else if (!String.IsNullOrEmpty(model.BtnExportExcel) || !String.IsNullOrEmpty(model.BtnExportExcelInitial))
                {
                    bool initial = !String.IsNullOrEmpty(model.BtnExportExcelInitial);
                    String fileName = null;
                    switch (oldModel.InstrumentType)
                    {

                        case InstrumentType.FixedIncome:
                            fileName = ExportExcelFixIncome(oldModel, initial);
                            break;
                        case InstrumentType.Equity:
                            fileName = ExportExcelEquity(oldModel, initial);
                            break;
                        case InstrumentType.UnitTrust:
                            fileName = ExportExcelUnitTrust(oldModel, initial);
                            break;
                        case InstrumentType.Derivatives:
                            break;
                        case InstrumentType.Loans:
                            break;
                        case InstrumentType.DepositAtFinancial:
                            fileName = ExportExcelDeposit(oldModel, initial);
                            break;

                    }

                    String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + fileName;
                    return Redirect(link);

                }
               
                else
                {
                    ViewBagUtil.SetError(ViewBag, "unknow operation ", null);
                }
            }
            catch (Exception ex)
            {

                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["InstructionFormModel"] = oldModel;
            return View(oldModel);
        }

        private IList<TransactionDataGridAdapter> GetSelectionDepositAtFinancial(InstructionFormModel model)
        {
            List<TransactionDataGridAdapter> result = new List<TransactionDataGridAdapter>();
            IList<InstructionDepositAtFinancialGridDetail> data = ServiceFactory.GetService().InstructionGetSelectionDepositData(model.ToInstructionFormScreenData());
            int Key = 0;
            foreach (var item in data)
            {
                TransactionDataGridAdapter adapter = new TransactionDataGridAdapter(item);
                adapter.Key = Key;
                result.Add(adapter);
                Key++;
            }

            return result;
        }
        private String ExportExcelDeposit(InstructionFormModel oldModel,bool initial)
        {

           
            if (oldModel.InstructionFormScreenDataCache == null)
                throw new Exception("InstructionFormScreenDataCache lost (ExportExcelDeposit)");
            ExcelWSService.ExcelWSClient client = new ExcelWSService.ExcelWSClient();
            client.Endpoint.ListenUri = new Uri(ConfigurationManager.AppSettings["ExcelServiceUrl"]);
            InstructionHeader insHeader = oldModel.InstructionFormScreenDataCache.Header;

            Company company = oldModel.InstructionFormScreenDataCache.CompanyList.Where(x => x.CompanyId == insHeader.CompanyID).SingleOrDefault();

            ExcelWSService.valueClass header = new ExcelWSService.valueClass();
            header.string1 = insHeader.TO;
            header.string2 = insHeader.Attention;
            header.string3 = insHeader.Mail;
            header.string4 = insHeader.FinancialInstrumentName;
            header.string5 = insHeader.TradeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string6 = insHeader.SettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string15 = company.CompanyContact;
            header.string7 = insHeader.CompanyName;
            header.string8 = insHeader.CompanyTel;
            header.string9 = insHeader.CompanyFax;
            header.string10 = insHeader.CompanyMail;
            if (company != null)
            {
                header.string11 = company.FixincomeSecuritiesAccount;
            }

            header.string13 = insHeader.CompanyName;
            header.string14 = insHeader.TO;
            String xlsName = WebUtil.GetReportExcelName("ExcelInstructionDepositOneGroup", initial); //"instruction_deposit_01";
            //decimal sum = 0;
           

            Dictionary<string, List<TransactionDataGridAdapter>> data = new Dictionary<string, List<TransactionDataGridAdapter>>();
            List<String> key = new List<string>();
            foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
            {
                DepositInstructionDetail detaildata = item.ToDepositInstructionDetail();
                if (data.ContainsKey(detaildata.InstructionTransactionType))
                {
                    data[detaildata.InstructionTransactionType].Add(item);
                }
                else
                {
                    List<TransactionDataGridAdapter> list = new List<TransactionDataGridAdapter>();
                    list.Add(item);
                    data.Add(detaildata.InstructionTransactionType, list);
                    key.Add(detaildata.InstructionTransactionType);
                }
            }

            if (key.Count == 1)
            {
                List<ExcelWSService.valueClass> detail = new List<ExcelWSService.valueClass>();
                List<TransactionDataGridAdapter> itemData = data[key[0]];
                foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                {
                    DepositInstructionDetail detailData = item.ToDepositInstructionDetail();
                    ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                    value.string1 = detailData.InstructionAccountVoucerNO;
                    value.string2 = detailData.InstructionTransactionType;
                    value.string3 = String.Format("{0}-{1}", detailData.InstructionBankName, detailData.InstructionBranchName);
                    value.string4 = detailData.InstructionTerm;
                    if (detailData.InstructionSettlementDate.HasValue)
                        value.string5 = detailData.InstructionSettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");
                    if (detailData.InstructionMaturityDate.HasValue)
                        value.string6 = detailData.InstructionMaturityDate.GetValueOrDefault().ToString("dd/MM/yyyy");
                    value.string7 = detailData.InstructionTypeofpayment;
                    value.string8 = detailData.InstructionRefNO;
                    value.double1 = (double)detailData.InstructionInterestRate.GetValueOrDefault();
                    value.double2 = (double)detailData.InstructionAmount.GetValueOrDefault();
                    header.double1 += value.double2;
                    detail.Add(value);
                }
                return client.export1(xlsName, header, detail.ToArray());
            }
            else if (key.Count == 2)
            {
                List<ExcelWSService.valueClass> detail1 = new List<ExcelWSService.valueClass>();
                List<ExcelWSService.valueClass> detail2 = new List<ExcelWSService.valueClass>();
                List<TransactionDataGridAdapter> itemData = data[key[0]];
                foreach (var item in itemData)
                {
                    ExcelWSService.valueClass value1 = new ExcelWSService.valueClass();
                    DepositInstructionDetail detailData = item.ToDepositInstructionDetail();
                    //  ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                    value1.string1 = insHeader.CompanyName;
                    value1.string2 = detailData.InstructionTransactionType;
                    value1.string3 = String.Format("{0}-{1}", detailData.InstructionBankName, detailData.InstructionBranchName);
                    value1.string4 = insHeader.AssetClassName;
                    value1.string5 = detailData.InstructionAccountVoucerNO;
                    value1.string6 = detailData.InstructionTypeofpayment;
                    if (detailData.InstructionSettlementDate.HasValue)
                        value1.string7 = detailData.InstructionSettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");


                    value1.double2 = (double)detailData.InstructionAmount.GetValueOrDefault();
                    header.double1 += value1.double2;
                    detail1.Add(value1);
                }
                List<TransactionDataGridAdapter> itemData2 = data[key[1]];
                foreach (var item in itemData2)
                {
                    ExcelWSService.valueClass value1 = new ExcelWSService.valueClass();
                    DepositInstructionDetail detailData = item.ToDepositInstructionDetail();
                    //   ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                    value1.string1 = insHeader.CompanyName;
                    value1.string2 = detailData.InstructionTransactionType;
                    value1.string3 = String.Format("{0}-{1}", detailData.InstructionBankName, detailData.InstructionBranchName);
                    value1.string4 = insHeader.AssetClassName;
                    value1.string5 = detailData.InstructionAccountVoucerNO;
                    value1.string6 = detailData.InstructionTypeofpayment;
                    if (detailData.InstructionSettlementDate.HasValue)
                        value1.string7 = detailData.InstructionSettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");


                    value1.double2 = (double)detailData.InstructionAmount.GetValueOrDefault();
                    header.double2 += value1.double2;
                    detail2.Add(value1);
                }
                return client.export2(WebUtil.GetReportExcelName("ExcelInstructionDepositTwoGroup", initial), header, detail1.ToArray(), detail2.ToArray());
            }
            else
            {
                throw new Exception("Many TransactionType (>2)");
            }
        }




        private String ExportExcelEquity(InstructionFormModel oldModel, bool initial)
        {
            if (oldModel.InstructionFormScreenDataCache == null)
                throw new Exception("InstructionFormScreenDataCache lost (ExportExcelEquity)");
            ExcelWSService.ExcelWSClient client = new ExcelWSService.ExcelWSClient();
            client.Endpoint.ListenUri = new Uri(ConfigurationManager.AppSettings["ExcelServiceUrl"]);
            InstructionHeader insHeader = oldModel.InstructionFormScreenDataCache.Header;

            Company company = oldModel.InstructionFormScreenDataCache.CompanyList.Where(x => x.CompanyId == insHeader.CompanyID).SingleOrDefault();

            ExcelWSService.valueClass header = new ExcelWSService.valueClass();
            header.string1 = insHeader.TO;
            header.string2 = insHeader.Attention;
            header.string3 = insHeader.Mail;
            header.string4 = insHeader.FinancialInstrumentName;
            header.string5 = insHeader.TradeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string6 = insHeader.SettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string15 = company.CompanyContact;
            header.string7 = insHeader.CompanyName;
            header.string8 = insHeader.CompanyTel;
            header.string9 = insHeader.CompanyFax;
            header.string10 = insHeader.CompanyMail;
            if (company != null)
            {
                header.string11 = company.FixincomeSecuritiesAccount;
            }

            header.string13 = insHeader.CompanyName;
            header.string14 = insHeader.TO;
            String xlsName = WebUtil.GetReportExcelName("ExcelInstructionEquity", initial);// "instruction_equity";
            //decimal sum = 0;
            List<ExcelWSService.valueClass> detail = new List<ExcelWSService.valueClass>();
            foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
            {
               EquityInstructionDetail detailData = item.ToEquityInstructionDetail();
                ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                value.string1 = insHeader.CompanyName;
                value.string2 = detailData.SecName;
                value.string3 = detailData.TransactionType;
                value.string4 = detailData.CounterpartyName;
                value.double1 = detailData.Unit.GetValueOrDefault();
                value.double2 = (double)detailData.PriceUnit.GetValueOrDefault();
                value.double3 = (double)detailData.GrossAmount.GetValueOrDefault();
                value.double4 = (double)detailData.ComAmount.GetValueOrDefault();
                value.double5 = (double)detailData.VatAmount.GetValueOrDefault();
                value.double6 = (double)detailData.PurchaseValueNet.GetValueOrDefault();
                value.double7 = (double)detailData.WHTaxAmount.GetValueOrDefault();
                value.double8 = (double)detailData.NetSettle.GetValueOrDefault();
                value.string5 = detailData.TypeofpaymentName;
                value.string6 = detailData.RefNO;


                header.double1 += value.double1;
                header.double3 += value.double3;
                header.double4 += value.double4;
                header.double5 += value.double5;
                header.double6 += value.double6;
                header.double7 += value.double7;
                header.double8 += value.double8;
             
              
                detail.Add(value);
            }



            return client.export1(xlsName, header, detail.ToArray());
        }

        private String ExportExcelUnitTrust(InstructionFormModel oldModel, bool initial)
        {
            if (oldModel.InstructionFormScreenDataCache == null)
                throw new Exception("InstructionFormScreenDataCache lost (ExportExcelUnitTrust)");
            ExcelWSService.ExcelWSClient client = new ExcelWSService.ExcelWSClient();
            client.Endpoint.ListenUri = new Uri(ConfigurationManager.AppSettings["ExcelServiceUrl"]);
            InstructionHeader insHeader = oldModel.InstructionFormScreenDataCache.Header;
           
            Company company = oldModel.InstructionFormScreenDataCache.CompanyList.Where(x => x.CompanyId == insHeader.CompanyID).SingleOrDefault();

            ExcelWSService.valueClass header = new ExcelWSService.valueClass();
            header.string1 = insHeader.TO;
            header.string2 = insHeader.Attention;
            header.string3 = insHeader.Mail;
            header.string4 = insHeader.FinancialInstrumentName;
            header.string5 = insHeader.TradeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string6 = insHeader.SettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string15 = company.CompanyContact;
            header.string7 = insHeader.CompanyName;
            header.string8 = insHeader.CompanyTel;
            header.string9 = insHeader.CompanyFax;
            header.string10 = insHeader.CompanyMail;
            if (company != null)
            {
                header.string11 = company.FixincomeSecuritiesAccount;
            }

            header.string13 = insHeader.CompanyName;
            header.string14 = insHeader.TO;
            String xlsName = WebUtil.GetReportExcelName("ExcelInstructionUnittrustList", initial);
            //decimal sum = 0;
            List<ExcelWSService.valueClass> detail = new List<ExcelWSService.valueClass>();
            foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
            {
                UnitTrustInstructionDetail detailData = item.ToInstructionDetailUnitTrust();
                ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                value.string1 = insHeader.CompanyName;
                value.string2 = detailData.FundName;
                value.string3 = detailData.TransactionType;
                value.string4 = detailData.CounterpartyName;
                value.double1 = detailData.Unit.GetValueOrDefault();
                value.double2 = (double)detailData.PriceUnit.GetValueOrDefault();
                value.double3 = (double)detailData.GrossAmount.GetValueOrDefault();
                value.double4 = (double)detailData.ComAmount.GetValueOrDefault();
                value.double5 = (double)detailData.VatAmount.GetValueOrDefault();
                value.double6 = (double)detailData.PurchaseValueNet.GetValueOrDefault();
                value.double7 = (double)detailData.WHTaxAmount.GetValueOrDefault();
                value.double8 = (double)detailData.NetSettle.GetValueOrDefault();
                value.string5 = detailData.TypeofpaymentName;
                value.string6 = detailData.RefNO;

   
                header.double2 += value.double1;
                header.double3 += value.double3;
                header.double4 += value.double4;
                header.double5 += value.double5;
                header.double6 += value.double6;
                header.double7 += value.double7;
                header.double8 += value.double8;
                //todo: hardcode
                if (detailData.ListedStatus != "1")
                    xlsName = WebUtil.GetReportExcelName("ExcelInstructionUnittrustNonList", initial);// "instruction_unit trust_Non Listed";
                detail.Add(value);
            }



            return client.export1(xlsName, header, detail.ToArray());
        }
        private String ExportExcelFixIncome(InstructionFormModel oldModel, bool initial)
        {
            if (oldModel.InstructionFormScreenDataCache == null)
                throw new Exception("InstructionFormScreenDataCache lost (ExportExcel)");
            ExcelWSService.ExcelWSClient client = new ExcelWSService.ExcelWSClient();
            client.Endpoint.ListenUri = new Uri(ConfigurationManager.AppSettings["ExcelServiceUrl"]);
            InstructionHeader insHeader = oldModel.InstructionFormScreenDataCache.Header;

            Company company = oldModel.InstructionFormScreenDataCache.CompanyList.Where(x => x.CompanyId == insHeader.CompanyID).SingleOrDefault();

            ExcelWSService.valueClass header = new ExcelWSService.valueClass();
            header.string1 = insHeader.TO;
            header.string2 = insHeader.Attention;
            header.string3 = insHeader.Mail;
            header.string4 = insHeader.FinancialInstrumentName;
            header.string5 = insHeader.TradeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string6 = insHeader.SettlementDate.GetValueOrDefault().ToString("dd/MM/yyyy");
            header.string7 = insHeader.CompanyName;
            header.string8 = insHeader.CompanyTel;
            header.string9 = insHeader.CompanyFax;
            header.string10 = insHeader.CompanyMail;
            if (company != null)
            {
                header.string11 = company.FixincomeSecuritiesAccount;
            }

            header.string13 = insHeader.CompanyName;
            header.string14 = insHeader.TO;

            decimal sum = 0;
            List<ExcelWSService.valueClass> detail = new List<ExcelWSService.valueClass>();
            foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
            {
                sum += item.PurchaseValue_LocalTHB.GetValueOrDefault();
                ExcelWSService.valueClass value = new ExcelWSService.valueClass();
                value.string1 = insHeader.CompanyName;
                value.string2 = item.Symbol;
                value.string3 = item.IsinCode;
                value.string4 = item.TransactionType;
                value.string5 = item.CounterParty;
                value.double1 = item.TransactionUnit;
                value.double2 = (double) item.CostYield_YTM;
                value.double3 = (double)item.PurchaseValue_LocalTHB.GetValueOrDefault();
                value.string6 = item.MaturityDate.GetValueOrDefault().ToString("dd/MM/yyyy");
                value.string7 = item.TypeOfPaymentName;
                value.string8 = item.RefNo;

                detail.Add(value);
            }

            header.string12 = sum.ToString();

            return client.export1( WebUtil.GetReportExcelName("ExcelInstructionFixincome", initial), header, detail.ToArray());
        }

        private InstructionFormScreenData UpdateOrInsert(InstructionFormModel model, InstructionFormModel oldModel)
        {
            InstructionFormScreenData result = null;


            if (model.Updatemode)
            {
                if (oldModel.InstructionFormScreenDataCache != null)
                {
                    if (oldModel.InstrumentType == InstrumentType.FixedIncome)
                    {

                        List<InstructionDetail> detailList = new List<InstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                        InstructionHeader header = oldModel.InstructionFormScreenDataCache.Header;
                     
                        foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                        {
                            if (item.InstructionDetailID == 0)//ตัวเพิ่งจะเลือกมา
                                detailList.Add(item.ToInstructionDetailFixIncome());
                        }
                        result = ServiceFactory.GetService().SaveInstructionFixIncome(header, detailList.ToArray());
                    }
                    else if (oldModel.InstrumentType == InstrumentType.UnitTrust)
                    {
                        List<UnitTrustInstructionDetail> detailList = new List<UnitTrustInstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                        InstructionHeader header = oldModel.InstructionFormScreenDataCache.Header;
                        foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                        {
                            UnitTrustInstructionDetail detail = item.ToInstructionDetailUnitTrust();
                            if (detail.DetailID == 0)//ตัวเพิ่งจะเลือกมา
                            {
                                //UnitTrustInstructionDetail detail = item.ToInstructionDetailUnitTrust();
                                detail.CreateBY = SessionManager.UserID(Session);
                                detailList.Add(detail);
                               // detailList.Add(item.ToInstructionDetailUnitTrust());
                            }
                        }
                        result = ServiceFactory.GetService().SaveInstructionUnitTrust(header, detailList.ToArray());

                    }
                    else if (oldModel.InstrumentType == InstrumentType.Equity)
                    {
                        List<EquityInstructionDetail> detailList = new List<EquityInstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                        InstructionHeader header = oldModel.InstructionFormScreenDataCache.Header;
                        foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                        {
                            EquityInstructionDetail detail = item.ToEquityInstructionDetail();
                            if (detail.DetailID == 0)//ตัวเพิ่งจะเลือกมา
                            {

                               
                                detail.CreateBY = SessionManager.UserID(Session);
                                detailList.Add(detail);

                               // detailList.Add(item.ToEquityInstructionDetail());
                            }
                        }
                        result = ServiceFactory.GetService().SaveInstructionEquity(header, detailList.ToArray());

                    }
                    else if (oldModel.InstrumentType == InstrumentType.DepositAtFinancial)
                    {
                        List<DepositInstructionDetail> detailList = new List<DepositInstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                        InstructionHeader header = oldModel.InstructionFormScreenDataCache.Header;
                        foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                        {
                            DepositInstructionDetail detail = item.ToDepositInstructionDetail();
                            if (detail.DepositInstructionDetailID == 0)//ตัวเพิ่งจะเลือกมา
                            {

                              //  DepositInstructionDetail detail = item.ToDepositInstructionDetail();
                                detail.CreateBY = SessionManager.UserID(Session);
                                detailList.Add(detail);

                                // detailList.Add(item.ToEquityInstructionDetail());
                            }
                        }
                        result = ServiceFactory.GetService().SaveInstructionDeposit(header, detailList.ToArray());

                    }
                }
                else
                {
                    throw new Exception("Data Error InstructionFormScreenDataCache lost");
                }
            }
            else //insert mode
            {
                InstructionHeader header = new InstructionHeader();
               
                header.Attention = model.Attn;
                SelectListItem selItem = oldModel.FinancialInstrumentList.Where(x => x.Value == model.FinancialInstrument).SingleOrDefault();
                if (selItem != null)
                {
                    header.FinancialInstrumentID = DataConverter.ConvertStringToIntNull(model.FinancialInstrument);
                    header.FinancialInstrumentName = selItem.Text;
                }
                Company comm = oldModel.InstructionFormScreenDataCache.CompanyList.Where(x => x.CompanyId == DataConverter.ConvertStringToIntNull(model.Company).GetValueOrDefault()).SingleOrDefault();
                if (comm != null)
                {
                    header.CompanyID = comm.CompanyId;
                    header.CompanyMail = comm.CompanyEmail;
                    header.CompanyName = comm.CompanyNameTh;
                    header.CompanyTel = comm.CompanyTel;
                    header.CompanyFax = comm.CompanyFax;
                }
                header.Mail = model.Email;
                header.SettlementDate = model.SettlementDate;
                header.TradeDate = model.TradeDate;
                header.TO = model.To;
                header.Status = "W";
                header.AssetClassID = DataConverter.ConvertStringToIntNull( model.FinancialInstrumentAssetClass);
                if (header.AssetClassID.HasValue)
                {
                    AssetClass asset = oldModel.InstructionFormScreenDataCache.AssetClassList.Where(x => x.AssetClassID == header.AssetClassID).SingleOrDefault();
                    if (asset != null)
                        header.AssetClassName = asset.AssetClassEN;
                }
                header.CreateUser = SessionManager.UserID(Session);
                if (oldModel.InstrumentType == InstrumentType.FixedIncome)
                {
                    List<InstructionDetail> detailList = new List<InstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                    foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                    {
                        
                        detailList.Add(item.ToInstructionDetailFixIncome());
                    }
                    result = ServiceFactory.GetService().SaveInstructionFixIncome(header, detailList.ToArray());
                }
                else if (oldModel.InstrumentType == InstrumentType.UnitTrust)
                {
                    List<UnitTrustInstructionDetail> detailList = new List<UnitTrustInstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                    foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                    {
                       UnitTrustInstructionDetail detail =  item.ToInstructionDetailUnitTrust();
                        detail.CreateBY = SessionManager.UserID(Session);
                        detailList.Add(detail);
                    }
                    result = ServiceFactory.GetService().SaveInstructionUnitTrust(header, detailList.ToArray());
                }
                else if (oldModel.InstrumentType == InstrumentType.Equity)
                {
                    List<EquityInstructionDetail> detailList = new List<EquityInstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                    foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                    {

                        EquityInstructionDetail detail = item.ToEquityInstructionDetail();
                        detail.CreateBY = SessionManager.UserID(Session);
                        detailList.Add(detail);

                      //  detailList.Add(item.ToEquityInstructionDetail());
                    }
                    result = ServiceFactory.GetService().SaveInstructionEquity(header, detailList.ToArray());
                }
                else if (oldModel.InstrumentType == InstrumentType.DepositAtFinancial)
                {
                    List<DepositInstructionDetail> detailList = new List<DepositInstructionDetail>(); //ต้องเป็นคัวที่จะไป insert
                    foreach (var item in oldModel.SelectedTransactionDataGridAdapterList)
                    {

                        DepositInstructionDetail detail = item.ToDepositInstructionDetail();
                        detail.CreateBY = SessionManager.UserID(Session);
                        detailList.Add(detail);

                        //  detailList.Add(item.ToEquityInstructionDetail());
                    }
                    result = ServiceFactory.GetService().SaveInstructionDeposit(header, detailList.ToArray());
                }
               
            }

            return result;

        }

        private void DelInstruction(String key, InstructionFormModel oldModel)
        {
            TransactionDataGridAdapter exist = oldModel.SelectedTransactionDataGridAdapterList.Where(x => x.Key == Convert.ToInt32(key)).SingleOrDefault();

            if (exist != null)
            {
              
                    var service = ServiceFactory.GetService();
                    if (oldModel.InstrumentType == InstrumentType.FixedIncome)
                    {
                        if (exist.InstructionDetailID != 0)
                            service.DeleteInstructionFixIncome(new int[] { exist.InstructionDetailID });
                    }

                    if (oldModel.InstrumentType == InstrumentType.UnitTrust)
                    {
                        int delID = exist.ToInstructionDetailUnitTrust ().DetailID ;
                        if (delID != 0)
                            service.DeleteInstructionUnitTrust(new int[] { delID });
                    }

                    if (oldModel.InstrumentType == InstrumentType.Equity)
                    {
                        int delID = exist.ToEquityInstructionDetail().DetailID;
                        if (delID != 0)
                            service.DeleteInstructionEquity(new int[] { delID });
                    }
                    if (oldModel.InstrumentType == InstrumentType.DepositAtFinancial)
                    {
                        int delID = exist.ToDepositInstructionDetail().DepositInstructionDetailID;
                        if (delID != 0)
                            service.DeleteInstructionDeposit(new int[] { delID });
                    }
                  
                
                oldModel.SelectedTransactionDataGridAdapterList.Remove(exist);
            }
            else
                throw new Exception("ไม่พบรายการที่ลบ");
            

        }
        private void AddInstruction(InstructionFormModel model, InstructionFormModel oldModel)
        {

            if (model.Selected != null)
            {
              //  IList<TransactionDataGridAdapter> selectedList = new List<TransactionDataGridAdapter>();
                foreach (String selKey in model.Selected)
                {
                    TransactionDataGridAdapter seldata = oldModel.TransactionDataGridAdapterList.Where(x => x.Key == Convert.ToInt32(selKey)).Single();
                    TransactionDataGridAdapter exist = oldModel.SelectedTransactionDataGridAdapterList.Where(x => x.Key == Convert.ToInt32(selKey)).SingleOrDefault();

                    //if (exist == null)
                    //{
                    //    oldModel.SelectedTransactionDataGridAdapterList.Add(seldata);
                    //} else
                    //    throw new Exception("รายการที่เลือกได้เคยเลือกไว้แล้ว");
                    oldModel.TransactionDataGridAdapterList.Remove(seldata);
                    oldModel.SelectedTransactionDataGridAdapterList.Add(seldata);
                }

            }
            else
            {
                throw new Exception("โปรดเลือกอย่างน้อย 1 รายการ");
            }
        }
        private List<TransactionDataGridAdapter> ToGridData(IList<InstructionDataDTO> data)
        {
            List<TransactionDataGridAdapter> gridData = new List<TransactionDataGridAdapter>();
            int Key = 0;
            foreach (var item in data)
            {
                TransactionDataGridAdapter adapter = new TransactionDataGridAdapter(item);
                adapter.Key = Key;
                gridData.Add(adapter);
                Key++;
            }
            return gridData;
        }
        private IList<TransactionDataGridAdapter> GetSelectionFixIncome(InstructionFormModel model)
        {
            IList<InstructionDataDTO> data = ServiceFactory.GetService().InstructionGetSelectionFixincomeData(model.ToInstructionFormScreenData());


            return ToGridData(data);
        }

        private IList<TransactionDataGridAdapter> GetSelectionUnitTrust(InstructionFormModel model)
        {
            List<TransactionDataGridAdapter> result = new List<TransactionDataGridAdapter>();
            IList<InstructionUnitTrustGridDetail> data = ServiceFactory.GetService().InstructionGetSelectionUnitTrustData(model.ToInstructionFormScreenData());
            int Key = 0;
            foreach (var item in data)
            {
                TransactionDataGridAdapter adapter = new TransactionDataGridAdapter(item);
                adapter.Key = Key;
                result.Add(adapter);
                Key++;
            }

            return result;
        }

        private IList<TransactionDataGridAdapter> GetSelectionEquity(InstructionFormModel model)
        {
            List<TransactionDataGridAdapter> result = new List<TransactionDataGridAdapter>();
            IList<InstructionEquityGridDetail> data = ServiceFactory.GetService().InstructionGetSelectionEquity(model.ToInstructionFormScreenData());
            int Key = 0;
            foreach (var item in data)
            {
                TransactionDataGridAdapter adapter = new TransactionDataGridAdapter(item);
                adapter.Key = Key;
                result.Add(adapter);
                Key++;
            }

            return result;
        }
       

 
    }
}
